# coding:utf-8
"""
description:Home management页面
"""
import os
import random

from common.Database import Query
from common.Log import LOG
from pages.Sidebar_page import sidebar_page
from appium.webdriver.common import mobileby
from common.Gesture_Mainpulation import gesture_mainpulation

from common.Get_Yaml import get_yaml
from config.GlobalParameter import TEST_Element_YAML

testElements = get_yaml(os.path.join(TEST_Element_YAML, "HomeMgt.yaml"))


class HomeManagement_page(sidebar_page):
    by = mobileby.MobileBy()

    # 右上角 HomeMgmt Create home，功能见test_CreateAndJoinHome.py
    btnHomeMgmtCreate_loc = (by.ID, testElements.get_elementInfo(0))

    def click_btnHomeMgmtCreate(self):
        """
        点击右上角 HomeMgmt Create home，功能见test_CreateAndJoinHome.py
        """
        self.find_element(*self.btnHomeMgmtCreate_loc).click()

    def func_EnterHomeMgmtCreate(self):
        """
        从HomeMgmt进入，点击右上角  Create home，弹框选择set up a new home
        :return:
        """
        super().click_homeicon()  # 点击dashboard页面的左上角三杆
        super().click_homemgmtLine()  # 点击side bar页面的Home mangement一行
        self.find_element(*self.btnHomeMgmtCreate_loc).click()

    # Home Mgmt 切换Picture
    btnHomeMgmtPic_loc = (by.ID, testElements.get_elementInfo(1))

    def click_btnHomeMgmtPic(self):
        """
        点击切换picture控件
        """
        self.find_element(*self.btnHomeMgmtPic_loc).click()

    # 点击手机recent的相册
    recentGallery_loc = (by.ANDROID_UIAUTOMATOR, testElements.get_elementInfo(17))

    def getAndClick_recentGallery(self):
        """随意获取手机recent相册（后续在选择手机capture+下面的图片），并点击"""
        getPics = self.find_elements(*self.recentGallery_loc)
        random.choice(getPics).click()

    def func_switchHomeMgmtPic(self, checkText):
        """
        切换home management图片
        :param checkText:
        :return:
        """
        self.click_btnHomeMgmtPic()
        self.getAndClick_recentGallery()
        return super().find_toast(checkText)

    # 点击home Mgmt name一行，获取name，修改的弹框element见Public.yaml（3、4、5）
    HomeMgmtName_loc = (by.ID, testElements.get_elementInfo(2))

    def click_HomeMgmtName(self):
        """
        点击home Mgmt name一行，修改的弹框element见Public.yaml（3、4、5）
        """
        self.find_element(*self.HomeMgmtName_loc).click()

    def get_HomeMgmtName(self):
        """
        获取home name
        :return: home name
        """
        return self.find_element(*self.HomeMgmtName_loc).text

    def func_testMgmtName(self, name, checkText):
        """
        验证Home Management Name输入框
        :param name:
        :param checkText: 输入内容错误，点击save后的提示内容
        :return:
        """
        self.click_HomeMgmtName()
        super().func_input_name(name)
        return super().find_toast(checkText)

    def func_MgmtName(self, name):
        """
        修改正确,home Mgmt name等于输入的name
        :param name:
        :return: False 和 Ture
        """
        super().click_ClosePopup()
        self.click_HomeMgmtName()
        self.input_EditName(name)
        self.click_InputPopupSave()
        return self.get_HomeMgmtName() == name

    # 点击Members一行，获取”x Members“ text
    HomeMgmtMembers_loc = (by.ID, testElements.get_elementInfo(3))

    def click_HomeMgmtMembers(self):
        """
        点击Members一行，获取”x Members“ text
        """
        self.find_element(*self.HomeMgmtMembers_loc).click()

    # members 头像右下角的role icon，无法区分master第一位，无法区分manager和member
    MemberRole_loc = (by.ID, testElements.get_elementInfo(13))

    def get_MemberRoleIcon(self):
        """
        members 头像右下角的role icon，一般master第一位，无法区分manager和member
        :return: 返回member page role的icon
        """
        return self.find_elements(*self.MemberRole_loc)

    # member info 页面，user name 下显示Administrator、Member和Master
    MemberSettingsRole_loc = (by.ID, testElements.get_elementInfo(18))

    def get_MemberSettingsRole(self):
        """
         member info 页面，user name 下显示Administrator、Member和Master
        :return: 返回获取的Administrator、Member和Master
        """
        return self.find_element(*self.MemberSettingsRole_loc).text

    # 点击set a Member 和 Set as Administrator
    MemberSettingsSetRole_loc = (by.ID, testElements.get_elementInfo(19))

    def click_MemberSettingsSetRole(self):
        """
        点击set a Member 和 Set as Administrator
        """
        self.find_element(*self.MemberSettingsSetRole_loc).click()

    # 点击REMOVE ADMINISTRATOR或REMOVE MEMBER按钮
    btnMemberSettingsRemove_loc = (by.ID, testElements.get_elementInfo(20))

    def click_btnMemberSettingsRemove(self):
        """
        点击REMOVE ADMINISTRATOR或REMOVE MEMBER按钮
        """
        self.find_element(*self.btnMemberSettingsRemove_loc).click()

    # 获取member page的数量，可获取name
    MemberName_loc = (by.ID, testElements.get_elementInfo(9))

    def get_MemberName(self):
        """
        获取member page的数量
        :return: 可获取name,len
        """
        return self.find_elements(*self.MemberName_loc)

    def func_MemberSettingsRole(self, role):
        """
        member info pag设置权限，随机点击member和admin进行互相授权
        :param role:
        :return:
        """
        self.click_HomeMgmtMembers()
        self.get_MemberName()[1].click()
        # random.choice(self.get_MemberName()).click()
        print(self.get_MemberSettingsRole())
        if self.get_MemberSettingsRole() == "Member":
            LOG.info("member info pag设置权限，从Member ==》Administrator。。。")
            self.click_MemberSettingsSetRole()
            self.assertVisibleAndClick_confirm()
            print(self.get_MemberSettingsRole() == role[0], self.get_MemberSettingsRole(), role[0])
            return self.get_MemberSettingsRole() == role[0]
        elif self.get_MemberSettingsRole() == "Administrator":
            LOG.info("member info pag设置权限，从Administrator ==》Member。。。")
            self.click_MemberSettingsSetRole()
            self.assertVisibleAndClick_confirm()
            print(self.get_MemberSettingsRole() == role[1], self.get_MemberSettingsRole(), role[1])
            return self.get_MemberSettingsRole() == role[1]
        else:
            LOG.info("member info pag设置权限，随机进入到master页面，直接退出操作。。。")
            super().click_btnBack()
            return True

    def func_MemberSettingRemove(self):
        """
        member删除，选择最后members page最后一个成员，点击remove按钮先取消后删除
        :param role:
        :returRn:
        """
        self.click_HomeMgmtMembers()
        MN = self.get_MemberName()
        LenMN = len(MN)  # 获取未删除角色的长度
        MN[-1].click()  # 点击Members page最后一个成员
        self.click_btnMemberSettingsRemove()
        super().click_cancel()
        self.click_btnMemberSettingsRemove()  # 重新点击确认删除
        super().click_confirm()
        return LenMN - 1 == len(self.get_MemberName())

    # 点击 SET AS ADMINISTRATOR 按钮
    btnApproveMemberAdmin_loc = (by.ID, testElements.get_elementInfo(14))

    def click_btnApproveMemberAdmin(self):
        """
        点击 SET AS ADMINISTRATOR 按钮
        """
        self.find_element(*self.btnApproveMemberAdmin_loc).click()

    # 点击 SET AS MEMBER 按钮
    btnApproveMemberMember_loc = (by.ID, testElements.get_elementInfo(15))

    def click_btnApproveMemberMember(self):
        """
        点击 SET AS MEMBER 按钮
        """
        self.find_element(*self.btnApproveMemberMember_loc).click()

    # 点击REJECT按钮
    btnApproveMemberReject_loc = (by.ID, testElements.get_elementInfo(16))

    def click_btnApproveMemberReject(self):
        """
        点击REJECT按钮
        """
        self.find_element(*self.btnApproveMemberReject_loc).click()

    def func_ApproveMember(self, message):
        """
        授权新加入的member，最后一位，随机进行Admin、Member和Reject操作
        :return:
        """
        self.click_HomeMgmtMembers()

        LenMN = len(self.get_MemberName())  # 获取未拒绝member的长度

        self.get_MemberRoleIcon()[-1].click()
        num = random.randint(1, 2)  # 随机三种操作
        if num == 1:
            LOG.info("授权新加入的member（最后一位）为Administrator。。。")
            self.click_btnApproveMemberAdmin()
            # self.get_MemberName()[-1].click()
            # return self.get_MemberSettingsRole() == "Administrator"   # 调试没成功
            return self.find_toast(message)
        elif num == 2:
            LOG.info("授权新加入的member（最后一位）为Member。。。")
            self.click_btnApproveMemberMember()
            # self.get_MemberName()[-1].click()
            # return self.get_MemberSettingsRole() == "Member"  # 调试没成功
            return self.find_toast(message)
        else:
            LOG.info("拒绝授权新加入的member（最后一位）。。。")
            self.click_btnApproveMemberReject()
            return LenMN - 1 == len(self.get_MemberName())

    # 点击Home QR Code一行
    HomeQRCodeline_loc = (by.ACCESSIBILITY_ID, testElements.get_elementInfo(4))

    def click_HomeQRCodeline(self):
        """
        点击Home QR Code一行
        """
        self.find_element(*self.HomeQRCodeline_loc).click()

    # 点击Home management SHARE THIS QR CODE按钮
    btnHomeMgmtShareQr_loc = (by.ID, testElements.get_elementInfo(5))

    def click_btnHomeMgmtShareQr(self):
        """
        点击Home management SHARE THIS QR CODE按钮
        """
        self.find_element(*self.btnHomeMgmtShareQr_loc).click()

    # 判断HomeMgmtQR 图片是否存在
    HomeMgmtQR_loc = (by.ID, testElements.get_elementInfo(21))

    def func_QRCode(self):
        """
        Home QR Code》点击测试later和share按钮
        """
        self.click_HomeQRCodeline()
        # self.click_HomeQRCodeline()
        # self.click_btnHomeMgmtShareQr()
        return self.assertVisible(*self.HomeMgmtQR_loc)

    # 点击room management一行，获取”x Rooms“text，页面详见RoomManagement.yaml
    HomeMgmtRoomMgmt_loc = (by.ID, testElements.get_elementInfo(6))

    def click_HomeMgmtRoomMgmt(self):
        """点击room management一行，获取”x Rooms“text，页面详见RoomManagement.yaml"""
        self.swipe_HMGTScrollView()
        self.find_element(*self.HomeMgmtRoomMgmt_loc).click()

    # swipe 后出现底部room management
    HMGTScrollView_loc = (by.CLASS_NAME, testElements.get_elementInfo(12))

    def swipe_HMGTScrollView(self):
        """swipe 后出现底部room management"""
        xy = gesture_mainpulation().centreXAndY(self.find_element(*self.HMGTScrollView_loc))
        self.driver.swipe(xy[0], xy[3] - 50, xy[0], xy[1] - 500, 200)

    # 点击leave home 按钮，pop-up element见Public.yaml（3，13，14）
    btnHomeMgmtLeave_loc = (by.ID, testElements.get_elementInfo(7))

    def click_btnHomeMgmtLeave(self):
        """点击leave home 按钮，pop-up element见Public.yaml（3，13，14）"""
        self.find_element(*self.btnHomeMgmtLeave_loc).click()

    # 头像单选框
    cbMemberAssignMaster_loc = (by.ID, testElements.get_elementInfo(8))

    def get_cbMemberAssignMaster(self):
        """头像单选框,get_attribute("checked")"""
        return self.find_elements(*self.cbMemberAssignMaster_loc)

    # confirm按钮，点击后直接切换成功
    btnMembersAssignMaster_loc = (by.ID, testElements.get_elementInfo(10))

    def click_btnMembersAssignMaster(self):
        """confirm按钮，点击后直接切换成功"""
        self.find_element(*self.btnMembersAssignMaster_loc).click()

    def func_HomeMgmtLeaveNull(self, checktext):
        """
        点击Leave home 按钮，当没有其他member或者没选择member时点击confirm
        :param checktext: 断言提示语
        :return:
        """
        self.click_btnHomeMgmtLeave()
        super().func_RandomXOrCancel()
        self.click_btnHomeMgmtLeave()
        super().click_btnDeletePopupDelete()  # 确认按钮

        if super().assertVisible(*self.MemberName_loc) == False:
            LOG.info("点击Leave home 按钮跳转页面后》没有member时点击confirm。。。")
            self.click_btnMembersAssignMaster()
            return super().find_toast(checktext)
        else:
            LOG.info("点击Leave home 按钮跳转页面后》没选择member时点击confirm。。。")
            self.click_btnMembersAssignMaster()
            return super().find_toast(checktext)

    def func_HomeMgmtLeave(self, ifname, message):
        """
        点击Leave home 按钮，选择好固定角色后confirm
        :param ifname: 固定member name
        :return:
        """
        if self.assertVisible(*self.MemberName_loc):
            LOG.info("点击Leave home 按钮跳转页面后》要选择的成员是：%s》》》" % ifname)
            for index, row in enumerate(self.get_MemberName()):
                if row.text == ifname:  # 指定leave home时成员名称
                    row.click()
            self.click_btnMembersAssignMaster()
            return super().find_toast(message)
        else:
            LOG.info("点击Leave home 按钮，没有成员可以进行选择，请检查home。。。")
            super().click_btnBack()  # 返回
            return False

    # 点击remove home 按钮，pop-up element见Public.yaml（3，13，14）
    btnHomeMgmtRemove_loc = (by.ID, testElements.get_elementInfo(11))

    def click_btnHomeMgmtRemove(self):
        """点击remove home 按钮，pop-up element见Public.yaml（3，13，14）"""
        self.find_element(*self.btnHomeMgmtRemove_loc).click()

    def func_RemoveRoom(self, message):
        """
        homemanagement 》点击remove home 按钮，取消后重新确认删除
        :param checktext:
        :return:
        """
        self.click_btnHomeMgmtRemove()
        super().func_RandomXOrCancel()
        self.click_btnHomeMgmtRemove()
        super().click_btnDeletePopupDelete()
        return super().find_toast(message)

    def func_AssertHome(self, sqls, para):
        """
        在数据库查出账号名下所有home，断言leave或者remove的home不存在
        :param sqls: sql语句
        :param para: sql参数或检查点文字
        :return:
        """
        for index, row in enumerate(Query(sqls, para["sqlpara"])):
            print("在数据库查出账号名下所有home---{}".format(row))
            if row[0] == para["home"]:
                return False
        return True
